package cn.gx.learn.security_boot_jwt_websocket.websocket_origin.config;
import cn.gx.learn.security_boot_jwt_websocket.springsecurity.JWT.JWTUtils;
import cn.gx.learn.security_boot_jwt_websocket.base.dal.database.User;
import com.nimbusds.jose.JOSEException;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;

import java.text.ParseException;
import java.util.Collections;
import java.util.List;

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        List<String> protocol = request.getHeaders().get("Sec-WebSocket-Protocol");
        if (protocol != null && protocol.size() > 0) {
            String protocolValue = protocol.get(0);
            if (protocolValue.contains(",")) {
                String[] protocols = protocolValue.split(",");
                if (protocols.length >= 2 && "token".equals(protocols[0].trim())) {
                    String token = protocols[1].trim();
                    try {
                        User user = JWTUtils.paserToken(token);
                        sec.getUserProperties().put("user", user);
                        // 设置响应协议，确认使用token协议
                        response.getHeaders().put("Sec-WebSocket-Protocol", Collections.singletonList("token"));
                    } catch (ParseException e) {
                        System.err.println("JWT解析失败: " + e.getMessage());
                        throw new RuntimeException("JWT解析失败", e);
                    } catch (JOSEException e) {
                        System.err.println("JWT验证失败: " + e.getMessage());
                        throw new RuntimeException("JWT验证失败", e);
                    }
                } else {
                    System.out.println("协议格式不正确或不是token协议");
                }
            } else {
                System.out.println("协议值不包含逗号分隔符");
            }
        } else {
            System.out.println("未找到Sec-WebSocket-Protocol头部");
        }
    }




}
